using System;
using System.Collections;
using System.Html;
using System.Runtime.CompilerServices;
using jQueryApi;

namespace Nsb.Classes
{
    [IgnoreNamespace]
    public static class Helpers
    {
        public static void NoOp()
        {
        }

        public static string MethodName(object o)
        {
            string[] s = ((string) o).Split(".");
            return s[s.Length - 1];
        }

        [AlternateSignature]
        public static extern jQueryEventHandler ClosureEv(Action<jQueryEvent, Dictionary> fn, Dictionary toClose);

        [AlternateSignature]
        public static extern jQueryEventHandler ClosureEv(Action<jQueryEvent, jQueryObject> fn, jQueryObject el);

        [AlternateSignature]
        public static extern jQueryEventHandler ClosureEv(Action<jQueryEvent, jQueryEventHandler> fn, jQueryEventHandler toClose);

        [AlternateSignature]
        public static extern jQueryEventHandler ClosureEv(Action<jQueryEvent, jQueryEventHandler> fn, jQueryEventHandler toClose, object arg2);

        public static jQueryEventHandler ClosureEv(Action<jQueryEvent, jQueryEventHandler, object, object> fn, jQueryEventHandler arg1, object arg2, object arg3)
        {
            return delegate(jQueryEvent e) { fn(e, arg1, arg2, arg3); };
        }

        public static bool StaticInheritClass(string cls1, string cls2)
        {
            Script.Literal("jQuery.extend(window[{1}], window[{0}])", cls1, cls2);
            Script.Literal("window[{0}] = window[{1}]", cls1, cls2);
            return true;
        }

        public static void InsertText(jQueryObject tx, string text)
        {
            Element input = tx[0];
            if (Type.GetScriptType(Type.GetField(input, "selectionStart")) != "undefined")
            {
                int top = input.ScrollTop;
                int start = (int)Type.GetField(input, "selectionStart");
                int end = (int)Type.GetField(input, "selectionEnd");
                string value = tx.GetValue();
                tx.Value(value.Substr(0, start) + text + value.Substr(end));
                Type.SetField(input, "selectionStart", start + text.Length);
                Type.SetField(input, "selectionEnd", start + text.Length);
                Type.SetField(input, "scrollTop", top);
                tx.Focus();
            }
            else Inform.Error("InsertText has no selectionStart");
        }
    }
}